<template>
  <div class="contain">
    <el-row :gutter="1">
      <el-form ref="ruleForm" :model="form" :rules="rules" label-width="80px">
        <el-col :span="6">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="状态" prop="state">
            <el-select v-model="form.state" placeholder="用户状态">
              <el-option label="正常" value="1"></el-option>
              <el-option label="停用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="small" @click="onSubmit">搜索</el-button>
            <el-button size="small" icon="el-icon-refresh" @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <div style="margin-bottom: 10px">
      <el-button icon="el-icon-plus" type="primary" plain size="mini" @click="addUser" >新增</el-button>
      <el-button icon="el-icon-delete" type="danger" plain size="mini"
                 :disabled="this.multipleSelection.length>0?false:true" @click="deleteAll">删除
      </el-button>
    </div>
    <el-table
        :data="tableData"
        :header-cell-style="{background:'rgb(242, 242, 242)'}"
        style="width: 100%;text-align: center"
        :row-style="{height: '50px'}"
        :cell-style="{padding: '0'}"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55"
          align="center"
      >
      </el-table-column>
      <el-table-column
          prop="username"
          label="用户名"
          width="100"
          align="center">
      </el-table-column>
      <el-table-column
          prop="nickName"
          label="昵称"
          width="100"
          align="center">
      </el-table-column>
      <el-table-column
          prop="sex"
          label="性别"
          width="100"
          align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.sex==1">男</span>
          <span v-if="scope.row.sex==0">女</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="city"
          label="地址"
          width="140"
          align="center">
      </el-table-column>
      <el-table-column
          prop="deptName"
          label="部门"
          width="100"
          align="center">
      </el-table-column>
      <el-table-column
          prop="tel"
          label="联系方式"
          width="150"
          align="center">
      </el-table-column>
      <el-table-column
          label="角色"
          width="100"
          align="center">
        <template slot-scope="scope">
          <span style="padding-right: 4px" v-for="(item,index) in scope.row.roles" :key="index">{{ item.roleCh }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="是否启用" width="100" align="center">
        <template slot-scope="scope">
          <el-switch
              :value="scope.row.state"
              :active-value="1"
              :inactive-value="0"
              @change="changeSwitch(scope.row, $event)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
          align="center"
          width="100"
      >
      </el-table-column>
      <el-table-column label="操作" align="center"  fixed="right" >
        <template slot-scope="scope">
          <el-button type="text" size="small" icon="el-icon-edit" @click="update(scope.row)">编辑</el-button>
          <el-button type="text" size="small" icon="el-icon-delete" @click="deleteuser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 模糊查询的分页功能 -->
    <el-pagination
        :current-page="form.page"
        :page-size="form.limit"
        :page-sizes="[2, 4, 6]"
        :total="total"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next"
    >
    </el-pagination>

<!--    编辑页面的-->
    <el-dialog title="修改用户" :visible.sync="UserUpdate" width="30%" :before-close="cance">
      <el-form :model="updateform" ref="updateform" label-width="80px" :rules="updaterules">
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="updateform.nickName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="updateform.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="city">
          <el-input v-model="updateform.city"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="updateform.deptId" placeholder="请选择">
            <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.deptName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="roleId" multiple placeholder="请选择">
            <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleCh"
                :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="updateform.tel"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio v-model="updateform.state" :label="0">禁用</el-radio>
          <el-radio v-model="updateform.state" :label="1">启用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('updateform')">确 定</el-button>
        <el-button @click="cance">取 消</el-button>
      </div>
    </el-dialog>

<!--    增加页面-->
    <el-dialog title="添加用户" :visible.sync="UserAdd" width="30%" :before-close="addcance">
      <el-form :model="addform" ref="addform" label-width="80px" :rules="updaterules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addform.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="addform.nickName" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="addform.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地址" prop="city">
          <el-input v-model="addform.city" placeholder="请输入地址"></el-input>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="addform.deptId" placeholder="请选择部门">
            <el-option
                v-for="item in deptList"
                :key="item.id"
                :label="item.deptName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="roleId" multiple placeholder="请选择">
            <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleCh"
                :value="item.roleId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="tel">
          <el-input v-model="addform.tel" placeholder="请输入联系方式"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio v-model="addform.state" :label="0">禁用</el-radio>
          <el-radio v-model="addform.state" :label="1">启用</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addsubmit('addform')">确 定</el-button>
        <el-button @click="addcance">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {getUserList, updateState, getDeptInfor, updateUser, addUser, deleteUser, getRoleInfor} from "@/request/api";
import {mapMutations} from "vuex";

export default {
  name: "UserView",
  data() {
    var picValidator = (rule, value, callback) => {
          if (!this.roleId.length) {
            // 一定要写 callBack() 验证完成时调用的回调函数 https://github.com/yiminghe/async-validator
            callback(new Error('校验：角色不能为空，请选择'))
          } else {
            callback()
          }};
    //自定义角色选择校验
    // 自定义验证规则
    return {
      form: {
        page: 1,
        limit: 4,
      },
      rules: {},
      total: undefined,
      //存储用户的数据
      tableData: [],
      //批量删除的
      multipleSelection: [],
      //编辑页面弹窗控制
      UserUpdate: false,
      updateform: {},
      updaterules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10个字符', trigger: 'blur'}
        ],
        nickName: [
          {required: true, message: '请输入昵称', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10个字符', trigger: 'blur'}
        ],
        sex: [
          {required: true, message: '请选择性别', trigger: 'change'}
        ],
        deptId: [
          {required: true, message: '请选择部门', trigger: 'change'}
        ],
        roleId:[
          { required: true, validator: picValidator,trigger:'blur'}
        ],
        city: [
          {required: true, message: '请输入城市', trigger: 'blur'},
          {min: 1, max: 10, message: '长度在 1 到 10个字符', trigger: 'blur'}
        ],
        tel: [
          {required: true, message: '请输入电话号码', trigger: 'blur'},
          {min: 5, max: 10, message: '长度在 5 到 10个字符', trigger: 'blur'}
        ],
        state: [
          {required: true, message: '请选择角色状态', trigger: 'change'}
        ]
      },
      //部门信息
      deptList: {},
      //角色信息
      roleList:{},
      roleId:[],
      //增加用户
      UserAdd:false,
      addform:{},
    }
  },
  created() {
    this.getList()
  },
  methods: {
    ...mapMutations(['getusername']),
    //获取用户的所有数据
    getList() {
      getUserList(this.form).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.user
          this.total = res.data.total
        }
      }).catch(erro => {
        this.$message.error("请求失败")
      })
    },
    //模糊搜索提交
    onSubmit() {
      this.form.page = 1
      this.form.limit = 10
      this.getList()
    },
    //模糊搜索重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    //复选框选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 开关切换
    changeSwitch(row, val) {
      this.$confirm('确认要停用' + row.username + '用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateState(row.id, val).then(res => {
          if (res.code == 200) {
            this.$message.success(res.msg)
            this.getList()
            return
          }
        }).catch(erro => {
          this.$message.error("请求失败")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    //编辑
    update(row) {
       this.UserUpdate=true
       this.deptInfor()
       this.roleInfor()
      if(row.roles!=null){
        if(row.roles)
         row.roles.forEach(s=>{
           this.roleId.push(s.roleId)
         })
      }
       this.updateform=row
    },
    //获取部门信息
    deptInfor(){
      getDeptInfor().then(res=>{
        this.deptList=res.data
      }).catch(erro=>{
        this.$message.error("请求失败")
      })
    },
    //获取角色信息
    roleInfor(){
      getRoleInfor().then(res=>{
         if(res.code==200){
           this.roleList=res.data
         }
      }).catch(erro=>{
        this.$message.error("请求失败")
      })
    },
    //修改用户信息
    submit(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          const roleId=this.roleId
          const {id,nickName, sex, city,deptId,tel,state} = this.updateform
          updateUser({id,nickName, sex, city,deptId,tel,state,roleId}).then(res => {
            if (res.code == 200) {
              this.UserUpdate=false
              this.roleId=[]
              this.$message.success("修改成功")
              window.sessionStorage.setItem("nickName",nickName)
              this.getusername()
              this.getList()
              return
            }
            this.$message.error(res.msg)
          }).catch(erro => {
            this.$message.error("请求失败")
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    cance(){
      this.UserUpdate=false
      this.updateform={}
      this.roleId=[]
      this.$refs.updateform.clearValidate()
    },
    //增加用户
    addUser(){
      this.UserAdd=true
      this.$refs.addform.clearValidate()
      this.deptInfor()
      this.roleInfor()
    },
    //取消
    addcance(){
      this.UserAdd=false
      this.addform={}
      this.roleId=[]
      this.$refs.addform.clearValidate()
    },
    //提交
    addsubmit(formName){
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.addform.roleId=this.roleId
          addUser(this.addform).then(res => {
            if (res.code == 200) {
              this.UserAdd=false
              this.$message.success(res.msg)
              this.getList()
              this.addform={}
              this.roleId=[]
              return
            }
            this.$message.error(res.msg)
          }).catch(erro => {
            this.$message.error("请求失败")
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //批量删除
    deleteAll(){
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids=[]
        this.multipleSelection.forEach(s=>
            ids.push(s.id)
        )
        deleteUser(ids).then(res=>{
          if(res.code==200){
            this.$message.success(res.msg)
            this.getList()
            return
          }
          this.$message.error(res.msg)
        }).catch(erro=>{
          this.$message.error("请求失败")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    //删除
    deleteuser(id) {
      this.$confirm('确认要删除？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var ids=[]
        ids.push(id)
        deleteUser(ids).then(res=>{
          if(res.code==200){
            this.$message.success(res.msg)
            this.getList()
            return
          }
          this.$message.error(res.msg)
        }).catch(erro=>{
          this.$message.error("请求失败")
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消！'
        })
      })
    },
    //分页当前页面
    handleCurrentChange(val) {
      this.form.page=val
      this.getList()
    },
    handleSizeChange(val) {
      this.form.limit=val
      this.getList()
    }
  }
}
</script>

<style scoped>

</style>
